import { asyncRoutes, constantRoutes } from '@/router'
import { getList as getAuthMenu } from '@/api/router'
import Layout from '@/layout'

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.map(item => {
    // console.log(item.component)
    let component = Layout
    if (item.component) {
      component = () => import('@/views/datav/index')
    }
    item.component = component
    item.hidden = Boolean(item.hidden)
    if (item.children && item.children.length > 0) {
      const children = []
      item.children.forEach((citem) => {
        children.push({
          path: citem.path,
          name: citem.name,
          component: (resolve) => require([`@/views/${citem.component}`], resolve),
          hidden: Boolean(citem.hidden),
          meta: citem.meta
        })
      })
      delete item.children
      item.children = children
    }
    return item
  })
  return data
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, roles)
    }
    res.push(tmp)
  })
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  priviledges: [],
  currentModule: '',
  currentRoutes: {}
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    routes.push({
      path: '*',
      redirect: '/404',
      hidden: true
    })
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PRIVILEDGES: (state, priviledges) => {
    state.priviledges = priviledges
  },
  SET_CURRENT_MODULE: (state) => {
    const currentModule = window.location.href.split('/').slice(-1)[0]
    state.currentModule = currentModule
  },
  SET_CURRENT_ROUTES: (state, routes) => {
    state.currentRoutes = routes
  }
}

const actions = {
  generateRoutes({ commit }, params) {
    return new Promise(resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      getAuthMenu(params).then(response => {
        let data = response
        const roles = ['admin']
        if (response.errorCode !== 0) {
          this.$message.success('菜单数据加载异常')
        } else {
          data = response.data.menu
          Object.assign(loadMenuData, data)
          const asyncRoutesNew = generaMenu(asyncRoutes, loadMenuData)
          let accessedRoutes
          if (roles.includes('admin')) {
            accessedRoutes = asyncRoutesNew || []
          } else {
            accessedRoutes = filterAsyncRoutes(asyncRoutesNew, roles)
          }
          const priviledges = response.data.priviledges
          commit('SET_ROUTES', accessedRoutes)
          commit('SET_PRIVILEDGES', priviledges)
          commit('SET_CURRENT_MODULE')
          resolve(accessedRoutes)
          resolve(priviledges)
        }
        // generaMenu(asyncRoutes, data)
      }).catch(error => {
        console.log(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
